package org.lgiavedoni.android.franq.util.resource;

import java.io.File;
import java.io.IOException;

import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.service.phone.ContextService;

import android.os.Environment;

public class ResourceUtil {
	public static final ResourceUtil inst = new ResourceUtil();

	public static final String INI_PATH = "resource/";

	private ResourceUtil() {
	}

	public File getResource(File file) {
		if (file.exists())
			return file;
		return getResource(file.getAbsolutePath());
	}

	public boolean createResource(String path) {
		try {
			return new File(INI_PATH + path).createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public File getResource(String path) {
		try {

			File configFile = null;

			// Try to get the file from classpath
			configFile = new File(INI_PATH + path);

			if (!configFile.exists()) {
				try {
					// Try to get de file from classLoader
					if (this.getClass().getClassLoader().getResource(INI_PATH + path) != null)
						configFile = new File(this.getClass().getClassLoader().getResource(INI_PATH + path).toURI());
				} catch (Exception ex) {
					Logger.inst.debug(ex);
				}
			}

			if (!configFile.exists()) {
				// Try to get from the jar
				try {
					if (this.getClass().getResource(INI_PATH + path) != null)
						configFile = new File(this.getClass().getResource(INI_PATH + path).toURI());
				} catch (Exception ex) {
					Logger.inst.debug("Can't get the config file from the jar");
				}
			}

			// Try from the phone /data
			if (!configFile.exists()) {
				try {
					configFile = ContextService.inst.getApplicationContext().getFileStreamPath(path);
				} catch (Exception ex) {
					// NOTE: Exception when java.lang.IllegalArgumentException:
					// File httpService/home.html contains a path separator
				}
			}

			// Try from the phone /sdcard
			if (!configFile.exists()) {
				try {
					configFile = new File(Environment.getExternalStorageDirectory() + "/frank/" + path);
				} catch (Exception ex) {
				}
			}

			return configFile.exists() ? configFile : null;

		} catch (Exception e) {
			Logger.inst.error(e);
			return null;

		}

	}

}
